﻿using System;
using System.Windows.Forms;
using INHollandair.Core.Enum;
using INHollandair.Core.Models;
using INHollandair.Core.Services;

namespace INHollandair_log_application
{
    public partial class LoginForm : Form
    {
        private int _attempts;
        public LoginForm()
        {
            _attempts = 0;
            InitializeComponent();
            UserName.Focus();
            AcceptButton = LoginButton;
        }

        private void LoginButtonClick(object sender, EventArgs e)
        {
            string userName = UserName.Text;
            string password = Password.Text;

            if (userName.Length > 0 && password.Length > 0 && userName.Length <= 24 && password.Length <= 24)
            {
                UserService svc = new UserService();
                try
                {
                    string salt = svc.GetAdminSaltByName(userName);
                    string hash = salt == null ? String.Empty : EncryptionUtils.Hash(password, salt);

                    LoginEnum login = svc.LoginAdmin(userName, hash);
                    switch (login)
                    {
                        case LoginEnum.NotFound:
                            _attempts++;
                            ErrorLabel.Text = String.Format("Inlog pogingen over: {0}", (5-_attempts));
                            break;
                        case LoginEnum.NotActivated:
                            _attempts++;
                            ErrorLabel.Text = String.Format("Inlog pogingen over: {0}", (5 - _attempts));
                            break;
                        case LoginEnum.Succes:
                            DialogResult = DialogResult.OK;
                            break;
                }
    
                }
                catch (Exception)
                {
                    ErrorLabel.Text = String.Format("Verbinding mislukt.");
                }
                
                if(_attempts >= 5)
                {
                    DialogResult = DialogResult.Cancel;
                }
            }
        }
    }
}
